package com.hongfei.test.domain;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jhf
 * @description
 * @Date: 2025/4/20
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class AlipaySandboxSignVerify {
    // 支付宝公钥（从沙箱账户获取）
    private static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjWWhDPlDtcrw90MghvNTHRCVA3eUlLmML1/x1H9sn6NmhfPTCe55X2+oWrXMpbctZ1CgZZ/ORC3fe6Vk5d13VaQ4wPeLSDHiMG17Fyla9UoQPcy+ghkxxBwA0Bmk/ancfM6/zg2PTjKQibKXHvesJ3ubBf2dpe6AQOsLCORHk/w798aooOXsYDRZGY/XZWvu8jm9y+PGqaAvzV0Ofi6b/qLka7PDm1Eu96GblhQ0VnA6NJoGXubGO7zdsLSZacO93u1Og9lsygFT1BuQKmyU//ir/imdoa1DdNaIrCCYHsQiZVQPtwnIzUYuQ6L13d/60PfICJ+iAGoEaFdS6ZfGMwIDAQAB";

    @Test
    public static void main(String[] args) {
        // 模拟支付宝回调参数（实际应从回调请求中获取）
        Map<String, String> params = new HashMap<>();
        params.put("notify_time", "2025-04-21 10:10:10");
        params.put("notify_type", "trade_status_sync");
        params.put("notify_id", "12345678901234567890");
        params.put("trade_no", "202504211000000000");
        params.put("out_trade_no", "ORDER_123456");
        params.put("sign_type", "RSA2");
        params.put("sign", "模拟的签名值...需替换为真实签名");
        // 其他业务参数...

        try {
            // 验证签名（重点）
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    ALIPAY_PUBLIC_KEY,
                    AlipayConstants.CHARSET_UTF8,
                    AlipayConstants.SIGN_TYPE_RSA2);

            System.out.println("============= 验签结果 =============");
            System.out.println(signVerified ? "✅ 验签通过" : "❌ 验签失败");

            if (!signVerified) {
                System.out.println("可能原因：");
                System.out.println("1. 支付宝公钥不正确");
                System.out.println("2. 参数中有空格或编码问题");
                System.out.println("3. 签名(sign)被篡改");
            }
        } catch (AlipayApiException e) {
            System.err.println("验签过程出错：" + e.getMessage());
        }
    }
}
